﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AlexandriaPressAuthorObject;
using AlexandriaPressAuthorDataAccessLayer;
using System.Web;
using System.IO;
using System.Data;

namespace AlexandriaPressAuthorBusinessLayer
{
    public class BusinessAuthor
    {
        public List<Book> searchMyBookByGenreOrTitle(string bookGenre,int authorID)
        {
            return DataLayerAuthor.authSearchMyBookByGenreOrTitle(bookGenre,authorID);
        }

        public Book viewMyBook(int bookID,int authorID)
        {
            return DataLayerAuthor.authViewMyBook(bookID,authorID);
        }

        public string filePath()
        {
            return DataLayerAuthor.getPath();
        }

        public string imagePath()
        {
            return DataLayerAuthor.imagePath();
        }

        public string submitDraft(string Title, string genre, int authorID, string fileName, string filePath, string imagePath, HttpPostedFile filePosted, HttpPostedFile imagePosted, string imageName,string userEmail,string userName,string titleValidator)
        {
            if (Title != titleValidator)
            {

                fileName = fileName.Trim();
                filePath = filePath.Trim();
                imageName = imageName.Trim();
                imagePath = imagePath.Trim();
                Boolean fileOK = false;

                String fileExtension = Path.GetExtension(fileName).ToLower();
                String imageExtension = Path.GetExtension(imageName).ToLower();

                String[] allowedExtensions = { ".pdf", ".jpg", ".JPEG", ".png", ".bmp" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (imageExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }

                if (fileOK)
                {
                    if (!(filePath.Length > 8000))
                    {
                        FileInfo file = new FileInfo(filePath);
                        FileInfo imageFile = new FileInfo(imagePath);

                        if (!file.Exists && !(fileName.Length > 100))
                        {
                            if (!imageFile.Exists)
                            {
                                try
                                {
                                    int x = DataLayerAuthor.submitDraft(Title, DataLayerAuthor.imagePath() + imageName, genre, authorID, filePath, userEmail, userName);

                                    filePosted.SaveAs(filePath);
                                    imagePosted.SaveAs(imagePath);


                                    if (x > 0)
                                        return "Files Uploaded! Draft Submitted";
                                    else
                                        return "File could not be uploaded.";
                                }
                                catch
                                {
                                    return "File could not be uploaded.";
                                }
                            }
                            else
                                return "Please rename the image file";


                        }
                        else
                        {
                            return "Please rename the book file.";
                        }
                    }
                    else
                    {
                        return "Error - Please call an administrator";
                    }
                }
                else
                {
                    return "Cannot accept files of this type.";
                }
            }
            else
            {
                return "Title Already Exists";
            }
        }
       
        public int getAuthorID(string username)
        {
              return DataLayerAuthor.getAuthorID(username);

        }

        public Draft viewDraft(int draftID, int authorID)
        {
            return DataLayerAuthor.viewDraft(draftID, authorID);
        }

        public string publishDraftToSite(int draftID, string Title, string genre, int authorID, string description, int price, int stock)
        {
            Draft draft = DataLayerAuthor.getImageAndFileLocation(draftID);

            int validator = DataLayerAuthor.publishDraftToSite(Title, draft.BookCoverLocation, genre, authorID, draft.FileLocation, description, draftID, price, stock);

            if (validator == 1)
                return "Draft Published";
            else
                return "Failed";
        }

        public int editPrice(int bookID, int price)
        {
            bool validator = DataLayerAuthor.editPrice(bookID, price);
            if (validator)
                return price;
            else
                return 0;
        }

        public int getOverAllSale(int authorID)
        {
            int OverAllSale = new Int32();
            List<Order> lstOfOrder = new List<Order>();
            if (DataLayerAuthor.getOverAllSale(authorID) != null)
            {
                lstOfOrder = DataLayerAuthor.getOverAllSale(authorID);
                foreach (Order order in lstOfOrder)
                {
                    OverAllSale += (order.Price * order.Quantity);
                }
                return OverAllSale;
            }
            return 0;
        }

        public int getSaleOfBook(int authorID, string bookTitle)
        {
            int OverAllSale = new Int32();
            List<Order> lstOfOrder = new List<Order>();
            lstOfOrder = DataLayerAuthor.authBookSaleReport(bookTitle, authorID);
            foreach (Order order in lstOfOrder)
            {
                OverAllSale += (order.Price * order.Quantity);
            }
            return OverAllSale;
        }

        public List<Order> getListOfOrder(int authorID,string bookTitle)
        {
            List<Order> lstOfOrder =  DataLayerAuthor.authBookSaleReport(bookTitle, authorID);
            return lstOfOrder;
        }

        public List<Order> getListOfOrderByGenre(int authorID, string bookTitleorGenre,string typeGenreOrTitle)
        {
            if (typeGenreOrTitle != null)
            {
                if (bookTitleorGenre != null)
                {
                    if (typeGenreOrTitle == "Title")
                    {
                        return DataLayerAuthor.authBookSaleReport(bookTitleorGenre, authorID);
                    }
                    else if (typeGenreOrTitle == "Genre")
                        return DataLayerAuthor.getSaleReportByGenre(bookTitleorGenre, authorID);
                }

            }
            return null;
        }

        public List<Order> getListOfOverallSale(int authorID)
        {

            return  DataLayerAuthor.getOverAllSale(authorID);

        }

        public int getSaleReporTByGenreOrTitle(int authorID, string typeGenreOrTitle, string genreOrTitle)
        {
            if (typeGenreOrTitle == "Genre")
            {
                int OverAllSale = new Int32();
                List<Order> lstOfOrder = new List<Order>();
                lstOfOrder = DataLayerAuthor.getSaleReportByGenre(genreOrTitle, authorID);
                foreach (Order order in lstOfOrder)
                {
                    OverAllSale += (order.Price * order.Quantity);
                }
                return OverAllSale;
            }
            else if (typeGenreOrTitle == "Title")
            {
                int OverAllSale = new Int32();
                List<Order> lstOfOrder = new List<Order>();
                lstOfOrder = DataLayerAuthor.authBookSaleReport(genreOrTitle, authorID);
                foreach (Order order in lstOfOrder)
                {
                    OverAllSale += (order.Price * order.Quantity);
                }
                return OverAllSale;
            }
            else
                return 0;
        }
        
        public string checkDraftTitle(string draftTitle,int authorID)
        {
            return DataLayerAuthor.checkDraftTitle(draftTitle,authorID);
        }

        public string drftVldtrIfExists(string draftTitleInDB, string titleSubmit)
        {
            if (draftTitleInDB == titleSubmit)
                return "You already have a Draft or Book with this Title. Please try another one.";
            else
                return "";
        }

        public List<Draft> viewApprovedDrafts(int authorID)
        {
            return DataLayerAuthor.viewApprovedDrafts(authorID);
        }

        public List<Draft> viewAllDrafts(int authorID)
        {
            return DataLayerAuthor.viewAllDrafts(authorID);
        }
        
        public DataTable createListOfDraft(List<Draft> lstOfDraft)
        {
            DataTable table = new DataTable();

            table.Columns.Add("ImageLocation");
            table.Columns.Add("Title");
            table.Columns.Add("Genre");
            table.Columns.Add("DateSubmitted");
            table.Columns.Add("Status");
            table.Columns.Add("Comments");
            table.Columns.Add("DraftID");

            foreach (Draft draft in lstOfDraft)
            {
                string approvalStatus = DataLayerAuthor.approvedDraftValidator(draft.ApprovalStatus);
                
                table.Rows.Add(draft.BookCoverLocation, draft.WorkingTitle, draft.Genre, draft.DateSubmitted.Day + "/" + draft.DateSubmitted.Month + "/" + draft.DateSubmitted.Year, approvalStatus, draft.Comments, draft.DraftID);
            }

            return table;

        }

        public DataTable createTableOfBooks(List<Book> lstOfBooks)
        {
            DataTable table = new DataTable();

            table.Columns.Add("ImageLocation");
            table.Columns.Add("Title");
            table.Columns.Add("Genre");
            table.Columns.Add("DatePublished");
            table.Columns.Add("Stock");
            table.Columns.Add("Description");
            table.Columns.Add("Price");
            table.Columns.Add("DatePriceWasSet");
            table.Columns.Add("BookID");

            foreach (Book book in lstOfBooks)
            {
                table.Rows.Add(book.BookCover, book.Title, book.Genre, book.DatePublished.Day + "/" + book.DatePublished.Month + "/" + book.DatePublished.Year, book.Stock.ToString(), book.Description, book.Price, book.DatePriceWasSet.Day + "/" + book.DatePriceWasSet.Month + "/" + (book.DatePriceWasSet.Year + 2000), book.BookID);
            }

            return table;
        }

        public DataTable createSaleTable(List<Order> lstOfOrder)
        {
            if (lstOfOrder != null)
            {
                DataTable table = new DataTable();

                table.Columns.Add("ImageLocation");
                table.Columns.Add("Title");
                table.Columns.Add("Price");
                table.Columns.Add("Stock");


                foreach (Order order in lstOfOrder)
                {
                    table.Rows.Add(order.ImageLocation, order.BookTitle, order.Price.ToString(), order.Quantity);
                }

                return table;
            }

            return null;
        }

        public List<Draft> viewDraftForEditing(int authorID)
        {
            return DataLayerAuthor.viewDraftsForEditing(authorID);
        }

        private string uploadImage(int authorID,string Title,string genre,HttpPostedFile imagePosted, string imageName, string imagePath,string oldFilePath,int draftID)
        {
            imageName = imageName.Trim();
            imagePath = imagePath.Trim();
            Boolean fileOK = false;

            String imageExtension = Path.GetExtension(imageName).ToLower();

            String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".bmp" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (imageExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }

             if (fileOK)
            {
                if (!(imagePath.Length > 8000))
                {
                    FileInfo file = new FileInfo(imagePath);
                    FileInfo imageFile = new FileInfo(imagePath);

                    if (!(imageName.Length > 100))
                    {
                            try
                            {
                                imagePosted.SaveAs(imagePath);
                                int x = DataLayerAuthor.editDraft(Title, DataLayerAuthor.imagePath() + imageName + imageName, genre, authorID, oldFilePath, draftID);
                                if (x > 0)
                                    return "File uploaded!";
                                else
                                    return "File could not be uploaded.";
                            }
                            catch
                            {
                                return "File could not be uploaded.";
                            }

                    }
                    else
                    {
                        return "Filename too long.";
                    }
                }
                else
                {
                    return "Error - Please call an administrator";
                }
            }
            else
            {
                return "Cannot accept files of this type.";
            }
        }

        private string uploadFile(int authorID, string Title, string genre, HttpPostedFile filePosted, string fileName, string filePath, string oldImagePath,int draftID)
        {
            fileName = fileName.Trim();
            filePath = filePath.Trim();
            Boolean fileOK = false;

            String fileExtension = Path.GetExtension(fileName).ToLower();

            String[] allowedExtensions = { ".pdf" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }

            if (fileOK)
            {
                if (!(filePath.Length > 8000))
                {
                    FileInfo file = new FileInfo(filePath);
                    FileInfo imageFile = new FileInfo(filePath);

                    if (!(fileName.Length > 100))
                    {
                       
                            try
                            {
                                filePosted.SaveAs(filePath);
                                int x = DataLayerAuthor.editDraft(Title, oldImagePath, genre, authorID, filePath,draftID);
                                if (x > 0)
                                    return "File uploaded!";
                                else
                                    return "File could not be uploaded.";
                            }
                            catch
                            {
                                return "File could not be uploaded.";
                            }


                    }
                    else
                    {
                        return "Filename too long.";
                    }
                }
                else
                {
                    return "Error - Please call an administrator";
                }
            }
            else
            {
                return "Cannot accept files of this type.";
            }
        }

        private string uploadFileAndImage(string Title, string genre, int authorID, string fileName, string filePath, string imagePath, HttpPostedFile filePosted, HttpPostedFile imagePosted, string imageName,int draftID)
        {

            fileName = fileName.Trim();
            filePath = filePath.Trim();
            imageName = imageName.Trim();
            imagePath = imagePath.Trim();
            Boolean fileOK = false;



            String fileExtension = Path.GetExtension(fileName).ToLower();
            String imageExtension = Path.GetExtension(imageName).ToLower();

            String[] allowedExtensions = { ".pdf", ".jpg", ".JPEG", ".png", ".bmp" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (imageExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }

            if (fileOK)
            {
                if (!(filePath.Length > 8000))
                {
                    FileInfo file = new FileInfo(filePath);
                    FileInfo imageFile = new FileInfo(imagePath);

                    if ((fileName.Length > 100))
                    {
                            try
                            {
                                filePosted.SaveAs(filePath);
                                imagePosted.SaveAs(imagePath);
                                int x = DataLayerAuthor.editDraft(Title, imagePath, genre, authorID, filePath,draftID);
                                if (x > 0)
                                    return "File uploaded!";
                                else
                                    return "File could not be uploaded.";
                            }
                            catch
                            {
                                return "File could not be uploaded.";
                            }

                    }
                    else
                    {
                        return "Filename too long.";
                    }
                }
                else
                {
                    return "Error - Please call an administrator";
                }
            }
            else
            {
                return "Cannot accept files of this type.";
            }

        }

        private string editDraftWithTitleorGenre(int draftID,string Title, string genre, int authorID, string oldFileLocation, string oldImageLocation)
        {
            DataLayerAuthor.editDraft(Title, oldImageLocation, genre, authorID, oldFileLocation,draftID);
            return "Draft Edited";
        }
        
        public string editDraft(int draftID,string Title, string genre, int authorID, string fileName, string filePath, string imagePath, HttpPostedFile filePosted, HttpPostedFile imagePosted, string imageName, string oldFileLocation, string oldImageLocation)
        {
                    if (filePosted.ContentLength == 0)
                    {
                        if (imagePosted.ContentLength == 0)
                            return editDraftWithTitleorGenre(draftID, Title, genre, authorID, oldFileLocation, oldImageLocation);
                        else
                            return uploadImage(authorID, Title, genre, imagePosted, imageName, imagePath, oldFileLocation,draftID);
                    }
                    else
                    {

                        if (imagePosted.ContentLength == 0)
                            return uploadFile(authorID, Title, genre, filePosted, fileName, filePath, oldImageLocation,draftID);
                        else
                            return uploadFileAndImage(Title, genre, authorID, fileName, filePath, imagePath, filePosted, imagePosted, imageName,draftID);

                    }

        }
        
        public bool validateUserIfAuthor(int userID)
        {
            if (DataLayerAuthor.validateUserTypeIfAuthor(userID) == DataLayerAuthor.userAuthorType())
                return true;
            return false;
        }

        public List<string> populateTitleOrGenreDrpDwn()
        {
            List<string> lstOfType = new List<string>();
            lstOfType.Add("Title");
            lstOfType.Add("Genre");

            return lstOfType;
        }

        public List<Order> getBookSaleByGenreOrTitle(string titleOrGenre,int authorID)
        {
            if (titleOrGenre == "Title")
                return DataLayerAuthor.authBookSaleReport(titleOrGenre, authorID);
            else if (titleOrGenre == "Genre")
                return DataLayerAuthor.getSaleReportByGenre(titleOrGenre, authorID);
            return null;
        }

        public bool publishValidator(string publishEvent)
        {
            if (publishEvent == "Draft Published")
                return true;
            return false;
        }

        public int getBookID(string title)
        {
            return DataLayerAuthor.getBookID(title);
        }
    }
}
